var version = 20
var dbName = 'users'
var tableUser = 'user'

//打开数据库
function openDb() {
    return new Promise((resolve, reject) => {
        //兼容浏览器
        var indexedDb = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
        var db;
        //打开数据库，没有创建自动创建
        //open(数据库名, version)
        var request = indexedDB.open(dbName, version);
        //打开成功
        request.onsuccess = function (e) {
            //拿到数据库实例
            db = e.target.result;
            console.log('数据库打开成功');
            resolve(db);
        }
        //打开失败
        request.onerror = function (e) {
            console.log('数据库打开报错');
            reject(e);
        }
        //数据库版本变更时运行
        //删除表，修改表，修改表时增加数据库版本号
        request.onupgradeneeded = function (e) {
            db = e.target.result;
            console.log('数据库版本有更新')
            createTableUser(db, tableUser)
            // deletetable(db,'user')
        }
    })
}

//修改字段，创建表，之前都要删除一下
//indexdb不支持修改表
function createTableUser(db, tname) {
    console.log('objectStoreNames',db.objectStoreNames)
    try {
        //判断表是否存在
        if (db.objectStoreNames.contains(tname)) {
            db.deleteObjectStore(tname)
            console.log('删除成功', tname)
        }
        //创建对象仓库(表名)
        var objectStore = db.createObjectStore(tname, {
            keyPath: 'id',//主键
            autoIncrement: true//自增，id不用添加
        });
        //创建索引,如果没有索引只能根据主键查询
        //unique：是否唯一
        objectStore.createIndex('id', 'id', {unique: true});
        objectStore.createIndex('name', 'name', {unique: false});
        objectStore.createIndex('age', 'age', {unique: false});
        objectStore.createIndex('banji', 'banji', {unique: false});
        console.log('更新表成功');

    } catch (e) {
        console.log('数据库创建失败');
    }

}

/**
 * @param db=数据库
 * @param storeName表名
 * @param data
 */
function add(db, storeName, data) {
    var request = db
        //transaction=创建事务
        //'readwrite':操作模式，读写
        .transaction([storeName], 'readwrite')
        //操作表名
        .objectStore(storeName)
        //插入
        .add(data);

    request.onerror = function (e) {
        console.log('数据添加失败=', e);
    }
    request.onsuccess = function (e) {
        console.log('数据添加成功');
    }
}

// 更新用户
function updateUser(db, user) {
    return new Promise((resolve, reject) => {
        const transaction = db.transaction(['user'], 'readwrite');
        const objectStore = transaction.objectStore('user');
        const request = objectStore.put(user);

        request.onsuccess = function () {
            resolve(request.result);
        };

        request.onerror = function (event) {
            reject(event.target.error);
        };
    });
}

// 删除用户
function deleteUser(db,tname, id) {
    return new Promise((resolve, reject) => {
        const transaction = db.transaction([tname], 'readwrite');
        const objectStore = transaction.objectStore(tname);
        const request = objectStore.delete(id);

        request.onsuccess = function () {
            resolve();
            console.log('删除成功')
        };

        request.onerror = function (event) {
            reject(event.target.error);
            console.log('删除失败',event.target.error)
        };
    });
}
// 根据多个索引删除数据
function deleteUserByNameAndAge(db, tableName, name, age) {
    return new Promise((resolve, reject) => {
        const transaction = db.transaction([tableName], 'readwrite');
        const objectStore = transaction.objectStore(tableName);
        const index = objectStore.index('name');

        const request = index.openCursor(IDBKeyRange.only(name));

        request.onsuccess = function(event) {
            const cursor = event.target.result;
            if (cursor) {
                if (cursor.value.age === age) {
                    cursor.delete();
                    console.log(`删除 name 为 ${name} 且 age 为 ${age} 的记录`);
                }
                cursor.continue();
            } else {
                resolve();
            }
        };

        request.onerror = function(e) {
            console.error('数据删除失败', e);
            reject(e);
        };
    });
}

// 查询用户
function getUser(db, id) {
    return new Promise((resolve, reject) => {
        const transaction = db.transaction(['user'], 'readonly');
        const objectStore = transaction.objectStore('user');
        const request = objectStore.get(id);

        request.onsuccess = function () {
            resolve(request.result);
        };

        request.onerror = function (event) {
            reject(event.target.error);
        };
    });
}

// 获取所有用户
function getAllUsers(db) {
    return new Promise((resolve, reject) => {
        const transaction = db.transaction(['user'], 'readonly');
        const objectStore = transaction.objectStore('user');
        const request = objectStore.getAll();

        request.onsuccess = function () {
            resolve(request.result);
        };

        request.onerror = function (event) {
            reject(event.target.error);
        };
    });
}

//删除数据库
function deleteDatabase() {

    const deleteRequest = indexedDB.deleteDatabase(dbName);

    deleteRequest.onsuccess = function () {
        console.log('数据库删除成功');
    };

    deleteRequest.onerror = function (event) {
        console.error('数据库删除失败', event);
    };

    deleteRequest.onblocked = function () {
        console.warn('删除操作被阻塞');
    };
}

//删除表
function deletetable(db, storeName) {
    db.deleteObjectStore(storeName)
    console.log('删除成功', storeName)
}